<template>
    <section>
        <div style="margin-bottom:5px;">
            <div>{{parentNameShow}}下用户信息</div>
            <el-input placeholder="请输入内容" size="small" v-model="searchKey" style="width: 250px;">
                <el-button slot="append" size="small" icon="el-icon-search" @click="getDataList"></el-button>
            </el-input>
            <el-button type="primary" size="small" @click="openAddDialog()">新 建</el-button>
        </div>
        <el-table ref="multipleTable" :data="dataList" border tooltip-effect="dark" style="width: 100%"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" label="序号">
            </el-table-column>
            <el-table-column prop="name" label="名称">
            </el-table-column>
            <el-table-column prop="loginName" label="登录名">
            </el-table-column>
            <el-table-column label="创建人" width="120">
                <template slot-scope="scope">
                    <id-to-name :id="scope.row.createBy"
                                url="sys/org/common/getNameById/orgUserCommonService"></id-to-name>
                </template>
            </el-table-column>
            <el-table-column label="日期" width="180">
                <template slot-scope="scope">{{ scope.row.createTime }}</template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.status=='1'" type="success">启用</el-tag>
                    <el-tag v-else type="danger">禁用</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="250">
                <template slot-scope="scope">
                    <el-button-group>
                        <el-button size="mini" type="primary" @click="openDialog(scope.row)">编辑</el-button>
                        <el-button size="mini" type="primary" @click="openChangePwdDialog(scope.row.id)">修改密码</el-button>
                        <el-button size="mini" type="danger" @click="removeItem(scope.row)">删除</el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>
        <div style="text-align: right;background: rgb(239, 242, 247);border: 1px solid #E5E9F2;">
            <el-pagination style="line-height: 30px; height: 30px;" @size-change="handleSizeChange"
                           @current-change="handleCurrentChange" :current-page="currentPage"
                           :page-sizes="[10, 20, 30, 50]" :page-size="pageSize"
                           layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
        <el-dialog :title="dialogAddOrEdit" :visible="dialogFormVisibleAdd" :modal="dialogFormVisibleAdd"
                   :before-close="openAddDialogClose">

            <el-form label-width="100px" :rules="formAddRules" :model="formAdd" ref="formAdd">


                <el-row>
                    <el-col :span=12>
                        <el-form-item label="名称" prop="name">
                            <el-input v-model="formAdd.name" style="width: 100%"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=12>
                        <el-form-item label="登陆帐户" prop="loginName">
                            <el-input v-model="formAdd.loginName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span=12>
                        <el-form-item label="状态">
                            <el-switch on-text="启用" off-text="禁用" v-model="formAdd.status"></el-switch>
                        </el-form-item>
                    </el-col>
                    <el-col :span=12>
                        <el-form-item label="姓名拼音">
                            <el-input v-model="formAdd.namePinyin"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span=12>
                        <el-form-item label="性别">
                            <el-radio-group v-model="formAdd.sex">
                                <el-radio :label="0">男</el-radio>
                                <el-radio :label="1">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span=12>
                        <el-form-item label="电话">
                            <el-input v-model="formAdd.mobile"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span=12>
                        <el-form-item label="邮箱">
                            <el-input placeholder="请输入邮箱" v-model="formAdd.email"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=12>


                        <el-form-item label="身份证号码">
                            <el-input v-model="formAdd.idCard"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span=12>

                        <el-form-item label="出生日期">
                            <el-date-picker type="date" placeholder="选择日期" v-model="formAdd.birthDay"
                                            style="width: 100%;"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span=12>
                        <el-form-item label="工号">
                            <el-input v-model="formAdd.personNo"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span=12>
                        <el-form-item label="详细地址">
                            <el-input v-model="formAdd.address"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=12>


                        <el-form-item label="密码" prop="password" v-if="formAdd.id ==null">
                            <el-input v-model="formAdd.password"></el-input>
                        </el-form-item>
                    </el-col>


                </el-row>
                <el-row>
                    <el-col :span=24>
                        <el-table
                                :data="formAdd.userDeptRel"
                                border
                                style="width: 100%">
                            <el-table-column
                                    label="部门"
                                    　>
                                <template slot-scope="scope">
                                    <el-form-item label-width="0px" :prop="'userDeptRel.' + scope.$index + '.deptName'"
                                                  :rules="formAddRules.deptName">
                                        <el-input v-model="scope.row.deptName" 　style="width:85%"></el-input>
                                        <span class="select" @click="selectUserDialog(scope.$index)">选择</span>

                                    </el-form-item>


                                </template>
                            </el-table-column>
                            <el-table-column
                                    label="岗位"
                                    　>
                                <template slot-scope="scope">
                                    <el-form-item label-width="0px" :prop="'userDeptRel.' + scope.$index + '.postId'"
                                                  :rules="formAddRules.postId">
                                        <el-select v-model="scope.row.postId" placeholder="请选择">
                                            <el-option v-for="val in postList" :key="val.id" :value="val.id"
                                                       :label="val.name"/>


                                        </el-select>

                                    </el-form-item>


                                </template>
                            </el-table-column>
                            <el-table-column
                                    label="是否主部门">
                                <template slot-scope="scope">
                                    <el-form-item label-width="0px" :prop="'userDeptRel.' + scope.$index + '.major'"
                                    >
                                        <el-switch on-text="是" off-text="否" v-model="scope.row.major"></el-switch>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="100px" 　:render-header="renderHeader" 　>
                                <template slot-scope="scope">
                                    <el-button-group>
                                        <el-button size="mini" type="danger" @click="renderRemoveRow(scope.$index)">
                                            删除
                                        </el-button>
                                    </el-button-group>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <el-form-item>
                    <el-button type="primary" @click="submitFormAdd('formAdd')">保存</el-button>
                    <el-button @click="openAddDialogClose">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <div v-if="userDialogVisible">
            <user-dialog :DialogVisible="userDialogVisible"
                         :params="{user: selectUser,orgType:orgTypeValue}"
                         @on-dialog-change="onDialogChange"
                         :only="true"
            ></user-dialog>
        </div>
        <div v-if="ChangePwdDialogVisible">
            <userChangePwd :DialogVisible="ChangePwdDialogVisible"
                         :userId="userId"
                           @on-dialog-change="onChangePwdDialogChange"
            ></userChangePwd>
        </div>
    </section>
</template>
<style>

</style>
<script>

    import {AjaxByAll} from '@/api/api';
    import userChangePwd from '@/views/common/userChangePwd.vue'
    import idToName from '@/views/common/IdToName.vue';
    import userDialog from '@/views/common/userDialog.vue'

    export default {
        name: "sysOrgUserList",
        data() {

            return {
                dataList: [],
                multipleSelection: [],
                dialogFormVisibleAdd: false,
                labelPosition: 'left',
                formAdd: {
                    id: null,
                    name: null,
                    loginName: null,
                    password: null,
                    namePinyin: null,
                    sex: 0,
                    mobile: null,
                    email: null,
                    idCard: null,
                    birthDay: null,
                    address: null,
                    personNo: null,
                    status: true,
                    userDeptRel: []


                },
                defaultData: null,
                pageSize: 10,
                currentPage: 1,
                total: 0,
                dialogAddOrEdit: '',
                searchKey: null,
                formAddRules: {

                    name: [
                        {required: true, message: '请填写名称', trigger: 'blur'}
                    ],
                    loginName: [
                        {required: true, message: '请输入登陆名', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'}
                    ],
                    postId: [
                        {required: true, message: '请选择岗位', trigger: 'blur'}
                    ],
                    deptName: [
                        {required: true, message: '请选择部门', trigger: 'blur'}
                    ]
                },
                userDialogVisible: false,
                selectUser: [],
                orgTypeValue: 1,
                parentName: null,
                parentNameShow: null,
                useDeptIndex: null,
                postList: [],
                ChangePwdDialogVisible:false,
                userId:null
            }
        },

        methods: {
            openChangePwdDialog(id){
                this.ChangePwdDialogVisible=false;
              this.userId=id;
                this.$nextTick(function () {
                    this.ChangePwdDialogVisible=true;
                })
            },
            onChangePwdDialogChange(val) {
                this.ChangePwdDialogVisible =false;
            },
            getPostList() {
                let urls = 'sys/org/post/postList';
                let method = 'get';
                let form = {};
                AjaxByAll(method, urls, form).then(data => {
                    if (data.code === 200) {
                        this.postList = data.data;
                    } else {
                        this.$message.error(data.msg);
                    }
                });


            },
            renderHeader(h, params) {
                let a = [h('el-button', {
                    props: {
                        size: "mini",
                        type: "primary"
                    },
                    on: {
                        click: () => {
                            this.renderAddRow();
                        }
                    }
                }, '增加')];
                return h('div', a);
            }
            ,

            renderAddRow() {
                this.formAdd.userDeptRel.push({deptId: "", deptName: "", major: false, postId: "", postName: ""});
            }
            ,
            renderRemoveRow(index) {

                this.formAdd.userDeptRel.splice(index, 1);
            },
            getParentInfo(parentId) {
                if (parentId) {
                    let urls = 'sys/org/dept/' + parentId;
                    let method = 'get';
                    let form = {};
                    AjaxByAll(method, urls, form).then(data => {
                        if (data.code === 200) {
                            this.parentName = data.data.name;
                            this.parentNameShow = data.data.name;
                        } else {
                            this.$message.error(data.msg);
                        }
                    });
                } else {
                    this.parentNameShow = "根部门";
                }
            },
            openDialog(model) {

                if (model) {
                    this.getPostList();
                    let id = model.id;
                    this.dialogAddOrEdit = '编辑用户';
                    let urls = 'sys/org/user/' + id;
                    let method = 'get';
                    let form = {};
                    AjaxByAll(method, urls, form).then(data => {
                        if (data.code === 200) {
                            this.formAdd = data.data;
                        } else {
                            this.$message.error(data.msg);
                        }
                    });
                }
                this.dialogFormVisibleAdd = true;
            },
            openAddDialog() {
                this.dialogAddOrEdit = '新建用户';
                this.getPostList();
                // 送出後
                this.$data.formAdd = Object.assign(this.$data.formAdd, this.defaultData);
                this.formAdd.userDeptRel = [];
                this.formAdd.userDeptRel.push({
                    deptId: this.parentId,
                    deptName: this.parentName,
                    major: true,
                    postId: "",
                    postName: ""
                });
                this.dialogFormVisibleAdd = true;
            },
            openAddDialogClose() {

                this.dialogFormVisibleAdd = false;
            },

            getDataList() {
                let self = this;
                let form = {
                    currentPage: self.currentPage,
                    pageSize: self.pageSize,
                    keyword: self.searchKey,
                    parentId: self.parentId,
                };
                let urls = 'sys/org/user/query';
                AjaxByAll('post', urls, form).then(data => {
                    if (data.code === 200) {

                        self.total = data.data.total * 1;
                        self.dataList = data.data.records;
                    }

                    this.loading = false;
                });
            },
            submitFormAdd(formName) {

                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let form = this.formAdd;
                        let urls = 'sys/org/user/';
                        let method = this.formAdd.id
                        == null ? 'post' : 'put';
                        AjaxByAll(method, urls, form).then(data => {
                            if (data.code === 200) {
                                this.formAdd.id = data.data;
                                this.$message({
                                    message: '操作成功',
                                    type: 'success'
                                });

                                this.getDataList();
                            } else {
                                this.$message({
                                    message: data.msg,
                                    type: 'error'
                                });
                            }
                            this.dialogFormVisibleAdd = !this.dialogFormVisibleAdd;
                        });


                    } else {
                        this.$message({
                            message: '校验失败',
                            type: 'error'
                        });
                    }
                });
            },
            removeItem(model) {
                this.$confirm('确认移除吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    AjaxByAll('delete', 'sys/org/user/' + model.id, null).then(data => {
                        if (data.code === 200) {
                            this.$message({
                                message: '操作成功',
                                type: 'success'
                            });
                            this.getDataList();
                        } else {
                            this.$message({
                                message: '操作失败：' + data.msg,
                                type: 'error'
                            });
                        }

                    });
                }).catch(() => {

                });
            },
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row);
                    });
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageSize = val;
                this.getDataList();
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.currentPage = val;
                this.getDataList();
            },
            onDialogChange(val) {
                this.userDialogVisible = val.visible;
                if (val.users.length > 0) {
                    this.formAdd.userDeptRel[this.useDeptIndex].deptId = val.users[0].id;
                    this.formAdd.userDeptRel[this.useDeptIndex].deptName = val.users[0].name;
                }
                this.selectUser = [];
            },
            selectUserDialog(index) {
                this.useDeptIndex = index
                this.userDialogVisible = true;
                if (this.formAdd.userDeptRel != null && this.formAdd.userDeptRel[index].deptId !== '') {
                    this.selectUser[0] = {
                        id: this.formAdd.userDeptRel[index].deptId,
                        name: this.formAdd.userDeptRel[index].deptName
                    };
                }
            }
        },
        created() {
            this.defaultData = JSON.parse(JSON.stringify(this.formAdd));
        },
        mounted: function () {
            this.getDataList();
            this.getParentInfo(this.parentId);

        }, components: {
            userDialog,
            idToName,
            userChangePwd
        }, props: ['parentId']
    }
</script>
